package org.hbbTlias2025.service.IMPL;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.hbbTlias2025.mapper.StudentMapper;
import org.hbbTlias2025.pojo.Student;
import org.hbbTlias2025.pojo.StudentQueryParam;
import org.hbbTlias2025.pojo.pageReturn;
import org.hbbTlias2025.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
//    @LogOpreation
    public pageReturn<Student> getAllStudent(StudentQueryParam studentQueryParam) {

        try {
            PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());

            //2. 执行查询
            List<Student> empList = studentMapper.findAll(studentQueryParam);

            //3. 解析查询结果, 并封装
            Page<Student> p = (Page<Student>) empList;
            return new pageReturn<>((int) p.getTotal(), p.getResult());
        } catch (Exception e){
            System.out.println(e);
            return null;
        }

    }

    @Override
//    @LogOpreation
    public Student getStudentById(Integer id) {
        return studentMapper.getStudentById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());

        studentMapper.updateStudent(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStudentViolation(Integer id, Integer score) {
        Student thisStudent = studentMapper.getStudentById(id);

        thisStudent.setUpdateTime(LocalDateTime.now());
        Short countViolation = (short) (thisStudent.getViolationCount() + 1);
        Short scoreViolation = (short) (thisStudent.getViolationScore() + score);
        thisStudent.setViolationCount(countViolation);
        thisStudent.setViolationScore(scoreViolation);

        studentMapper.updateStudent(thisStudent);
    }

    @Override
    public void deleteIds(List<Integer> ids) {
        studentMapper.deleteIds(ids);
    }

    @Override
    public void addStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());

        studentMapper.addStudent(student);
    }
}
